/**
 * 
 */
package idv.takeshi.software.productline.bookstore.application.service.spring;

import org.apache.commons.lang.Validate;
import org.h2.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import idv.takeshi.software.productline.bookstore.application.service.MaintainUserAccountService;
import idv.takeshi.software.productline.bookstore.application.service.OriginalPasswordInvalidException;
import idv.takeshi.software.productline.bookstore.application.service.dto.UserAccountDto;
import idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount;
import idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccountRepository;

/**
 * @author takeshi
 *
 */
@Service("maintainUserAccountService")
@Transactional
public class MaintainUserAccountServiceImpl implements
		MaintainUserAccountService {
	
	@Autowired
	private UserAccountRepository userAccountRepository;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/* (non-Javadoc)
	 * @see idv.takeshi.software.productline.bookstore.application.service.MaintainUserAccountService#updateUserAccount(idv.takeshi.software.productline.bookstore.domain.model.useraccount.UserAccount, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public void updateUserAccount(UserAccountDto userAccountDto) throws OriginalPasswordInvalidException {
		Validate.notNull(userAccountDto, "userAccount shall always not be null");
		
		String encodedOriginalPassword = passwordEncoder.encodePassword(userAccountDto.getPassword(), null);
		UserAccount userAccount = this.userAccountRepository.findById(userAccountDto.getId());
		
		if(!StringUtils.equals(userAccount.getPassword(), encodedOriginalPassword)){
			throw new OriginalPasswordInvalidException("user given original password:" + 
					userAccountDto.getPassword() + " is invalid");
		}
		userAccountDto.loadModel(userAccount);
		
		String newEncodedPassword = this.passwordEncoder.encodePassword(userAccount.getOriginalPassword(), null);
		userAccount.setPassword(newEncodedPassword);
	}

}
